package com.gem.factory.log;

import com.gem.entity.Log;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author: Xhy
 * CreateTime: 2022-09-30 15:10
 * 游戏操作日志
 * 使用软引用维护
 */
public class LogFactory {

    static class ListReference extends SoftReference<PriorityQueue<Log>> {

        public ListReference(PriorityQueue<Log> referent) {
            super(referent);
        }
    }

    // key: 房间id  value： 日志(软引用)
    private static Map<String, ListReference> logs = new ConcurrentHashMap<>();


    /**
     * 添加记录
     * @param roomId
     * @param log
     */
    public static void add(String roomId,Log log){
        clear();
        if (logs.get(roomId) == null){
            create(roomId);
        }
        logs.get(roomId).get().add(log);
    }

    private static void create(String roomId){

        clear();
        ListReference reference = new ListReference(new PriorityQueue<Log>(new PriorityDateReversed()));
        logs.put(roomId,reference);
    }
    static class PriorityDateReversed implements Comparator<Log>{

        @Override
        public int compare(Log o1, Log o2) {
            return o2.getDate().compareTo(o1.getDate());
        }
    }

    public static void remove(String roomId){
        logs.remove(roomId);
    }

    public static PriorityQueue<Log> get(String roomId){
        clear();
        if (!exist(roomId)){
            return new PriorityQueue<>();
        }
        return LogFactory.logs.get(roomId).get();
    }

    private static boolean exist(String roomId){
        return logs.containsKey(roomId);
    }
    private static void clear(){
        logs.forEach((k,v)->{
            if (v.get() == null){
                logs.remove(k);
            }
        });
    }
}
